package com.aaa.zuul.filter;

import com.aaa.zuul.service.UserService;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: YuXin
 * @Date : Created in 2020/11/13 15:17
 * @ClassName : LoginFilter
 * @Description :
 * @Package_Name : com.aaa.zuul.filter
 */
@Component
public class LoginFilter extends ZuulFilter {

    @Autowired
    private UserService userService;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        //使用zuul包中提供请求上下文类获取请求上下文对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取request对象
        HttpServletRequest request = currentContext.getRequest();
        //获取response对象
        HttpServletResponse response = currentContext.getResponse();

        //获取请求地址
        String requestURI = request.getRequestURI();
        //获取token
        String accessToken = request.getParameter("accessToken");
        //判断是否是登录请求  判断是否带有token  正确也放行
        if (requestURI.contains("/ssoTokenController/userLogin") ||
                (!StringUtils.isEmpty(accessToken) && userService.checkToken(accessToken))) {
            currentContext.setSendZuulResponse(true);
            currentContext.setResponseStatusCode(200);
        } else {
            //拦截
            currentContext.setSendZuulResponse(false);
            try {
                response.getWriter().print("No Login");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
